/**
 * Created by Administrator on 2016/6/16 0016.
 */
var AppService = {
  urlroot: "http://euvee.vicp.co/rest/task/",

  init: function () {
    Vue.http.options.root = this.urlroot;
   /* Vue.http.options.emulateHTTP = true;
    Vue.http.options.emulateJSON = true;*/
  },
/*  newItem: function () {
    return newItem("0", true);
  },
  newItem: function (newid, newselected) {
    var item = {
      selected: newselected,
      id: newid,
      //rowid: null,
      owner: 'zhangsan@fd.com',
      description: "task description " + newid,
      deadline: '2015.07.08Z23:12:56:324:313',
      objectstate: null,
      rowstate: null,
      upduser: null,
      upddate: null,
      crtuser: null,
      crtdate: null,

      code: null,
      reluserid: 0,
      securitylevel: 0,
      idcard: null,
      firstname: "",
      midname: "",
      lastname: "",
      secname: "",
      nickname: "",
      respectname: "",
      gender: '*',
      email: "zhagnsan@163.com",
      mobilephone: "1373214421",
      im: "",
      qq: "",
      weixin: "",
      affiliation: "",
      employeeid: "",
      address: null,
      zip: null,
      birthday: null,
      sculpture: null,
      note: null,
      //
      node: '3211',
      name: "zhang san",
      timestamp: '2015.07.08Z23:12:56:324:313',
      frame: '56 7F 2A 3D',
      title: 'Go to grocery store',
      completed: false
    };
    return item;
  },
  resetItem: function (item) {
    item.selected = false;
    item.id = null;
    item.description = "";
    item.owner = null;
    item.objectstate = null;
    item.rowstate = null;
    item.upduser = null;
    item.upddate = null;
    item.crtuser = null;
    item.crtdate = null;

    item.code = null;
    item.reluserid = 0;
    item.securitylevel = 0;
    item.idcard = null;
    item.firstname = "";
    item.midname = "";
    item.lastname = "";
    item.secname = "";
    item.nickname = "";
    item.respectname = "";
    item.gender = '-';
    item.email = "zhagnsan@163.com";
    item.mobilephone = "1373214421";
    item.im = "";
    item.qq = "";
    item.weixin = "";
    item.affiliation = "";
    item.employeeid = "";
    item.address = null;
    item.zip = null;
    item.birthday = null;
    item.sculpture = null;
    item.objectstate = null;
    item.rowstate = null;
    item.note = null;
    item.upduser = null;
    item.upddate = null;
    item.crtuser = null;
    item.crtdate = null;
    item.note = null;
  },*/
  generate: function (inputQuery, pagenum, pagesteps, items, callback) {
    for (var i = 0; i < pagesteps; i++) {
      items.push(this.newItem(i, (i % 2 == 0)));
    }
    if (typeof callabck == "function")
      callback(items);
  },
  find: function(inputQuery, pagenum, pagesteps, items, success_callback, error_callback){
    var url = this.urlroot;
    Vue.http.get(url, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    })
  },

  find2: function(criterion, pagenum, pagesteps,success_callback, error_callback){
    Vue.http.get(this.urlroot+"?criterion=" + criterion + "&pagenum=" + pagenum + "&pagesteps=" + pagesteps, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    });
  },

  find3: function(id,success_callback, error_callback){
    Vue.http.get(this.urlroot+id, function (data, status, request) {
      success_callback(data, status, request)
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request)
      }
    });
  },
//
  edit:function(item,success_callback, error_callback){
    Vue.http.put(this.urlroot+JSON.stringify(item.content),function(data,status,request){
      success_callback(data, status, request)
    }).catch(function(data,status,request){
      error_callback(data,status,request)
    })
  },
  //显示详情
  details: function (item, success_callback, error_callback) {
    Vue.http.get(this.urlroot + item.id, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    )
  },
  //返回父级目录
  backToParent: function (p, success_callback, error_callback) {
    Vue.http.get(this.urlroot + p + "/children", function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  },
  backToParent2: function (parentid, success_callback, error_callback) {
    Vue.http.get(this.urlroot + parentid, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  },
  //切换节点
  change: function (item, success_callback, error_callback) {
    Vue.http.get(this.urlroot + item.id, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  },

  /* get an item with its detail information from the backend server.
   *
   * Callback: function(item, status, request)
   */
  get: function(id, callback){
    Vue.http.get(this.urlroot + this.id, callback);
  },

  getCachedItemById: function(items, id){
    var result = null;
    var i = items.length;
    while (i--) {
      if (items[i].id == id)
      {
        result = items[i];
        break;
      }
    }
    return result;
  },

  indexof: function(items, id){
    var idx = null;
    var i = items.length;
    while (i--) {
      if (items[i].id == id)
      {
        idx = i;
        break;
      }
    }
    return i;
  },

  /* Update an item with its detail information to the backend server.
   *
   * Callback: function(item, status, request)
   */
  set: function(id, item, success_callback, error_callback){
    // alert("svc.set " + item);
    // Vue.http.put({id:id}, {item:this.item}, success_callback).error(error_callback);
    $.ajax({
      data:JSON.stringify(item),
      type: "PUT",
      contentType: "application/json",
      url: urlroot + item.id,
      //url: "/site/mvc/member/" + item.id,
    })
  },
  add: function(item, success_callback, error_callback){
    Vue.http.post(this.urlroot, JSON.stringify(item), function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    });
  },
  remove: function(item, success_callback, error_callback){
    //	Vue.http.delete({id:id}, success_callback).error(error_callback);
    Vue.http.delete(this.urlroot+item.id, function (data, status, request) {      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    })
  },

  remove2: function(item, success_callback, error_callback){
    Vue.http.delete({id:id}, success_callback).error(error_callback);
  }
};
var svc = Object.create(AppService);
/*Vue.component('my-component', {
 template: '<div>A custom component!</div>'
 });*/
Vue.component('itemlist', {
  template: '#itemlist-tpl',
  mode: "modeList",

  props: {
    items: {
      type: Object,
      twoWay: false,
      required: true
    },
    mode: {
      type: String,
      default: 'modeList'
    },
    onEdit: {
      type: Function,
      required: true
    },
    onRemove: {
      type: Function,
      required: true
    },
    onChange: {
      type: Function,
      required: true
    }
  },

  components: {
    //list: { /* ... */ },
    //itemviewer: { /* ... */ },
    //'itemlist': itemeditor,
  },
  data: function () {
    return {
      result: null,
    }
  },

  methods: {
    onEditItem: function (item,e) {
      console.log("onSubmitClick: inside component itemelist");
      console.log("editor list"+item);

      //this.result = this.onSubmit(this.mode, this.item);
      this.result=this.onEdit(item,this.mode);
    },
    onRemoveItem: function (item,e) {
      console.log("onRemoveClick: inside component itemelist");
      vm.onRemoveItem(item,this.mode);
    },
    onChangeItem: function (item) {
      console.log("onChangeItem: inside component itemelist");
      vm.onChange(item);
    },
    backToParent: function (item) {
      console.log("onChangeItem: inside component itemelist");
      vm.backToParent(item);
    }
  },
  ready: function () {
  }
});
//Vue.component('my-component', MyComponent)
Vue.component('itemeditor', {
  template: '#itemeditor-tpl',
  mode: "modeEdit",

  props: {
    item: {
      type: Object,
      twoWay: false,
      required: true
    },

    mode: {
      type: String,
      default: 'modeList'
    },
    onSubmit: {
      type: Function,
      required: true
    },
    onCancel: {
      type: Function,
      required: true
    }
  },

  data: function () {
    return {
      result: null,
    }
  },

  methods: {
    onSubmitClick: function (e) {
      console.log("onSubmitClick: inside component itemeditor");
      // if (typeof callabck == "function")
      //	callback(items);
      console.log(typeof this.onSubmit);

      //this.result = this.onSubmit(this.mode, this.item);
      this.result=this.onSubmit(this.mode, this.item);
    },
    onCancelClick: function (e) {
      console.log("onCancelClick: inside component itemeditor");
      this.onCancel(this.mode, this.item);
    }
  },
  ready: function () {
    // this.onLoad('message from child!')
  }
});
var vm = new Vue({
  el: '#app',
  data: {
    currentView: 'itemeditor',
    criterion: '',
    pagenum: '',
    pagesteps: '',
    midname: '',
    lastname: '',
    remotedevice: '',
    searchQuery: '',
    items: [],
    items2: [],
    curitem: {},
    selectall: true,
    mode: 'modeList', // modeList, modeItemView, modeAddNew, modeEdit
    modeTitle: "",
    showModal: false,
    parentMsg: "test",
    curdate: "2016.06.16",
  },
  components: {
    //list: { /* ... */ },
    //itemviewer: { /* ... */ },
    //itemeditor: itemeditor,
  },
  methods: {
    __find: function (inputQuery, pagenum, pagesteps) {
      var self = this;
      svc.find('', pagenum, pagesteps, this.items, function (data, status, request) {
        // self.items.length = 0;
        self.$set('items', data);
        if (self.items.length > 0) {
          self.$set("curitem", self.items[0]);
        }
      }, function (data, status, request) {
        alert("Probably failed to connect the backend server! Pls check your server status!");
      });
    },
    _find: function (criterion, pagenum, pagesteps) {
      var self = this;
      svc.find2(criterion, pagenum, pagesteps, function (data, status, request) {
        // self.items.length = 0;
        self.$set('items', data);
        if (self.items.length > 0) {
          self.$set("curitem", self.items[0]);
        }
        // alert("vm.init: items.length = " + self.items.length);
        // alert(JSON.stringify(self.items));
      }, function (data, status, request) {
        alert("Probably failed to connect the backend server! Pls check your server status!");
      });
    },
    find: function (id) {
      var self = this;
      svc.find3(id, function (data, status, request) {
        self.$set("items", data);
        self.setMode('modeList');
      }, function (data, status, request) {
        alert("Probably failed to connect the backend server! Pls check your server status!");
      });
    },
    basicsearch: function (e) {
      this.searchQuery = this.searchQuery.trim();
      if ((this.searchQuery).length == 0) {
        document.getElementById("searchQuery").focus();
        alert("Please input search query");
      }
      this.find(this.searchQuery);
    },
    //===
    backToParent: function () {
      var self = this;
      var p = this.items2.parent;
      console.log("backToParent " + p);
      //根节点
      if (p == null) {
        svc.find('', '', '', this.items, function (data, status, request) {
          self.$set('items', data);
          self.$set('items2', null);
          if (self.items.length > 0) {
            self.$set("curitem", self.items[0]);
          }
        });
      } else {
        svc.backToParent(p, function (data, status, request) {
          self.$set('items', data);
          svc.backToParent2(p, function (data2, status, request) {
            self.$set('items2', data2)
          });
        });
      }
    },
    advancedsearch: function (e) {
      console.log("advanced search");
      console.log(e.target.tagName); // "BUTTON"
      console.log(e.targetVM === this); // true

      var inputs = new Array();
      inputs[0] = "{criterion:'";
      inputs[1] = this.criterion;
      inputs[2] = "', pagenum:'";
      inputs[3] = this.pagenum;
      inputs[4] = "', pagesteps:'";
      inputs[5] = this.pagesteps;
      inputs[6] = "', searchQuery:'";
      inputs[7] = this.searchQuery;
      inputs[8] = "'}";

      var inputQuery = inputs.join('');
      console.log("your input query condition is " + inputQuery);
      this._find(this.criterion, this.pagenum, this.pagesteps);
    },
    init: function () {
      svc.init();
      var datetime = new Date();
      datetime.getYear();        //获取当前年份(2位)
      datetime.getFullYear();    //获取完整的年份(4位,1970-????)
      datetime.getMonth();       //获取当前月份(0-11,0代表1月)
      datetime.getDate();        //获取当前日(1-31)
      datetime.getDay();         //获取当前星期X(0-6,0代表星期天)
      datetime.getTime();        //获取当前时间(从1970.1.1开始的毫秒数)
      datetime.getHours();       //获取当前小时数(0-23)
      datetime.getMinutes();     //获取当前分钟数(0-59)
      datetime.getSeconds();     //获取当前秒数(0-59)
      datetime.getMilliseconds();    //获取当前毫秒数(0-999)
      datetime.toLocaleDateString();     //获取当前日期
      this.curdate = datetime.toLocaleTimeString();     //获取当前时间
    },
    onSave: function (mode, item) {
      var uid = null;
      var self = this;
      console.log("onSave");
      if (mode == 'modeAddNew') {

        svc.add(item, function (data, status, request) {
          console.log("add success");
          // TODO add the item into vm.items[]
          //console.log(JSON.stringify(item));
          //vm.$set(self.items.push(item));
          //this.setMode('modeList');
          self.__find('', 1, 6);
        }, function (data, status, request) {
          alert("onSave failed to update!");
        });
        this.curitem={};
        this.setMode('modeList');
      }
      else {
        console.log("onEdit");
       /* self.$set("items.upduser", item.upduser);
        self.$set("items.curname", item.curname);*/
        svc.edit(item.id, item, function (item, status, request) {
          var idx = svc.indexof(this.items, item.id);
          if (idx != null) {
            vm.$set(this.items[idx], item);
          }
          // self.setMode('modeList');
        }, function (item, status, request) {
          alert("onSave failed to update!");
        });
      }
      setTimeout(function () {
        self.setMode('modeList');
      }, 20);
    },
    //切换节点信息
    onChange: function (item) {
      var self = this;
      svc.change(item, function (data, status, request) {
        self.$set('items', data);
        //显示详情
        svc.details(item, function (data2, status, request) {
          self.$set('items2', data2)
        });
      });
    },
    onCancel: function (mode, item) {
      console.log("onCancel");
      this.curitem={};
      this.setMode('modeList');
    },
    // TODO: test with backend
    onEdit: function (item, e) {
      console.log('editItem onEdit: ' + item.id);
      console.log('editItem onEdit item: ' + item);
      this.curitem = item;
      /*
       var detail = null;
       svc.get({id: item.id}, function (detail, status, request) {
       this.$set('curitem', detail)
       });
       */
      this.setMode('modeEdit');
    },
    onRemove: function (item, e) {
      console.log('onRemove' + item);
   /*   svc.remove(item,function(){
        self._find('', 1, 6);
      });*/
      /*console.log('remove: ' + item.id.toString());
      console.log('remove: ' + item);
      this.curitem = item;
      svc.remove(item,function(){
      });*/
      //this.items.$remove(item)
      //this.setMode('modeList');
    },

    onRemoveItem: function (item, e) {
      this.setMode('modeList');
      var self = this;
      var r = confirm("确定删除？");
      if (r == true) {
        svc.remove(item, function (data, status, request) {
            self._find('', 1, 6);
          }
        )
      }
      //this.items.$remove(item);
      //this.setMode('modeList');
    },
    onEditItem: function (item, e) {
      console.log('editItem' + item);
      svc.edit(item);
      this.setMode('modeList');
    },
    onRemoveSelected: function(e){
      console.log("removeSelected: " + e);
      var items = this.items;
      for (var i in items){
        if (items[i].selected)
        {
          console.log(items[i] + ' is to be deleted!!!');
          this.onRemoveItem(items[i], null);
        }
      }
    },
    setMode: function(newmode){
      if (this.mode != newmode)
      {
        switch (newmode)
        {
          case "modeList":
            this.modeTitle = "";
            break;
          case "modeItemView":
            this.modeTitle = " [详情]";
            break;
          case "modeEdit":
            this.modeTitle = " [编辑]";
            break;
          case "modeAddNew":
            this.modeTitle = " [新增]";
            //this.curitem.id=null;
            //svc.resetItem(this.curitem);
            this.curitem.id=null;
            break;
          default:
            this.modeTitle = "";
        }
        this.mode = newmode;
      }
    },
    getGender: function(value){
      var ret = '-';
      if (this.value == 'M')
        ret = '男';
      else if (this.value == 'F')
        ret = '女';
      return ret;
    }
  },
  ready: function(){
    console.log("ready function is called");
    this.__find('', 1, 6);
  }
});
setTimeout(function (){
  vm.init();
}, 20);
